// 和用户相关的状态管理
import {createSlice} from '@reduxjs/toolkit'
import { setToken as _setToken , getToken, removeToken, getUser, setUser } from '@/utils'
import authService from '../../services/authService'

const userStore=createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: getUser() || {}
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      // 持久化存储token
      _setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
      // 持久化存储用户信息
      setUser(action.payload)
    },
    clearUserInfo(state) {
      state.userInfo = {}
      state.token = ''
      removeToken()
    }
   }
})

//解构出actionCreators
const {setToken, setUserInfo, clearUserInfo} = userStore.actions
//获取reducer函数
const userReducer = userStore.reducer

//异步方法 完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        try {
            //1.发送异步请求
            const res = await authService.login(loginForm)
            if (res.success) {
                //2.提交同步action进行token的存入
                dispatch(setToken(res.data.token))
                dispatch(setUserInfo(res.data.user))
                return res
            } else {
                throw new Error(res.message || '登录失败')
            }
        } catch (error) {
            console.error('登录失败:', error)
            throw error
        }
    }
}

//获取个人信息异步方法
const fetchUserInfo = () => {
    return async (dispatch) => {
        try {
            const res = await authService.getUserInfo()
            if (res.success) {
                dispatch(setUserInfo(res.data))
                return res
            } else {
                throw new Error(res.message || '获取用户信息失败')
            }
        } catch (error) {
            console.error('获取用户信息失败:', error)
            throw error
        }
    }
}

export {fetchLogin, setToken, fetchUserInfo, clearUserInfo}
export default userReducer